package helpers;

import akka.actor.ActorRef;
import akka.actor.Props;
import akka.actor.UntypedActor;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import entities.Message;
import play.Logger;
import play.libs.Akka;
import play.libs.F;
import play.libs.Json;
import play.mvc.WebSocket;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: eagami
 * Date: 20/05/14
 * Time: 15:19
 * To change this template use File | Settings | File Templates.
 */
public class MessageActor extends UntypedActor {

    // Default Message.
    public static ActorRef defaultMessage = Akka.system().actorOf(Props.create(MessageActor.class));

    // Members of this room.
    private static List<WebSocket.Out<JsonNode>> members = new ArrayList<>();


    public static void join(WebSocket.In<JsonNode> in, WebSocket.Out<JsonNode> out) throws Exception{

        members.add(out);
        // For each event received on the socket,
        in.onMessage(new F.Callback<JsonNode>() {
            public void invoke(JsonNode event) {

                // Send a message .
                Logger.info("new browser connected");


            }
        });

        // When the socket is closed.
        in.onClose(new F.Callback0() {
            public void invoke() {

                Logger.info("browser disconnected");

            }
        });
    }



    public void onReceive(Object message) throws Exception {

        if(message instanceof Message)  {

            // Received a Talk message
            Message newMessage = (Message)message;

            notifyAll(newMessage);

        } else {
            unhandled(message);
        }

    }

    // Send a Json event to all members
    public static void notifyAll(Message message) {
        for(WebSocket.Out<JsonNode> channel: members) {

            ObjectNode event = Json.newObject();
            event.put("message", Json.toJson(message));

            channel.write(event);
        }
    }
}
